package think.in.spring.bean.registrar.annotaion;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;
import think.in.spring.bean.registrar.bean.AService;

import java.util.Map;

/**
 * ImportBeanDefinitionRegistrar接口
 * 接口定义了registerBeanDefinitions方法，可以编程方式注册Bean
 * 1.在处理@Configuration类，可以注册额外Bean类型(注意不是Bean实例),
 * 2.如果还实现了EnvironmentAware BeanFactoryAware BeanClassLoaderAware ResourceLoaderAware接口，
 * 这些接口的方法会在registerBeanDefinitions方法执行前执行
 * 应用场景:
 * 1.动态的注册Bean
 * 2.自定义类扫描器
 * 3.注册非Spring管理的Bean
 */
public class BeanClassRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                        BeanDefinitionRegistry registry,
                                        BeanNameGenerator importBeanNameGenerator) {
        Map<String, Object> beanClassMap = importingClassMetadata.getAnnotationAttributes(BeanClass.class.getName());
        System.out.println("beanClassMap:" + beanClassMap);
        Map<String, Object> beanClass1Map = importingClassMetadata.getAnnotationAttributes(BeanClass1.class.getName());
        System.out.println("beanClass1Map:" + beanClass1Map);
        Map<String, Object> compMap = importingClassMetadata.getAnnotationAttributes(Component.class.getName());
        System.out.println("compMap:" + compMap);
        Map<String, Object> importMap = importingClassMetadata.getAnnotationAttributes(Import.class.getName());
        System.out.println("importMap:" + importMap);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        System.out.println("registerBeanDefinitions");
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(AService.class);
        registry.registerBeanDefinition("aService",beanDefinition);
    }
}
